package cn.iocoder.yudao.module.promotion.controller.app.quickcombination;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.member.api.level.MemberLevelApi;
import cn.iocoder.yudao.module.member.api.level.dto.MemberLevelRespDTO;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.product.api.spu.ProductSpuApi;
import cn.iocoder.yudao.module.product.api.spu.dto.ProductSpuRespDTO;
import cn.iocoder.yudao.module.product.controller.app.spu.vo.AppProductSpuDetailRespVO;
import cn.iocoder.yudao.module.product.convert.spu.ProductSpuConvert;
import cn.iocoder.yudao.module.product.dal.dataobject.sku.ProductSkuDO;
import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.yudao.module.product.enums.spu.ProductSpuStatusEnum;
import cn.iocoder.yudao.module.product.service.sku.ProductSkuService;
import cn.iocoder.yudao.module.product.service.spu.ProductSpuService;
import cn.iocoder.yudao.module.promotion.controller.admin.quickcombinationactivity.vo.QuickCombinationActivityPageReqVO;
import cn.iocoder.yudao.module.promotion.controller.admin.quickcombinationactivity.vo.QuickCombinationActivityRespVO;
import cn.iocoder.yudao.module.promotion.controller.admin.quickcombinationactivity.vo.product.QuickCombinationProductRespVO;
import cn.iocoder.yudao.module.promotion.controller.admin.quickcombinationactivity.vo.record.QuickCombinationRecordRespVO;
import cn.iocoder.yudao.module.promotion.controller.admin.quickcombinationactivity.vo.record.QuickCombinationRecordSummary;
import cn.iocoder.yudao.module.promotion.controller.app.combination.vo.activity.AppCombinationActivityDetailRespVO;
import cn.iocoder.yudao.module.promotion.controller.app.combination.vo.activity.AppCombinationActivityRespVO;
import cn.iocoder.yudao.module.promotion.convert.combination.CombinationActivityConvert;
import cn.iocoder.yudao.module.promotion.convert.quickcombinationactivity.QuickCombinationActivityConvert;
import cn.iocoder.yudao.module.promotion.convert.quickcombinationactivity.QuickCombinationProductConvert;
import cn.iocoder.yudao.module.promotion.dal.dataobject.combination.CombinationActivityDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.combination.CombinationProductDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.quickcombinationactivity.QuickCombinationActivityDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.quickcombinationactivity.QuickCombinationProductDO;
import cn.iocoder.yudao.module.promotion.dal.mysql.quickcombinationactivity.QuickCombinationProductMapper;
import cn.iocoder.yudao.module.promotion.service.quickcombinationactivity.QuickCombinationActivityService;
import cn.iocoder.yudao.module.promotion.service.quickcombinationactivity.QuickCombinationRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.SPU_NOT_ENABLE;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.SPU_NOT_EXISTS;

@Tag(name = "用户 APP - 拼团活动")
@RestController
@RequestMapping("/promotion/quick-combination-activity")
@Validated
public class AppQuickCombinationActivityController {

    @Resource
    private QuickCombinationActivityService quickCombinationActivityService;

    @Resource
    private QuickCombinationProductMapper quickCombinationProductMapper;

    @Resource
    private ProductSpuApi productSpuApi;

    @Resource
    private QuickCombinationRecordService quickCombinationRecordService;

    @Resource
    private ProductSpuService productSpuService;

    @Resource
    private ProductSkuService productSkuService;

    @Resource
    private MemberUserApi memberUserApi;

    @Resource
    private MemberLevelApi memberLevelApi;

    @PostMapping("/page")
    @Operation(summary = "获得促销活动分页")
    public CommonResult<PageResult<QuickCombinationActivityRespVO>> getQuickCombinationActivityPage(@Valid @RequestBody QuickCombinationActivityPageReqVO pageVO) {
        PageResult<QuickCombinationActivityDO> pageResult = quickCombinationActivityService.getQuickCombinationActivityPage(pageVO);

        List<ProductSpuRespDTO> spus = productSpuApi.getSpuList(
                convertSet(pageResult.getList(), QuickCombinationActivityDO::getSpuId));

        return success(QuickCombinationActivityConvert.INSTANCE.convertPage(pageResult, spus));
    }

    @GetMapping("/get-sku")
    @Operation(summary = "获得商品 sku 明细")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<AppProductSpuDetailRespVO> getSpuDetail(@RequestParam("id") Long id) {
        QuickCombinationActivityDO activityDO = quickCombinationActivityService.getQuickCombinationActivity(id);

        // 获得商品 SPU
        ProductSpuDO spu = productSpuService.getSpu(activityDO.getSpuId());
        if (spu == null) {
            throw exception(SPU_NOT_EXISTS);
        }
        if (!ProductSpuStatusEnum.isEnable(spu.getStatus())) {
            throw exception(SPU_NOT_ENABLE);
        }

        List<QuickCombinationProductDO> products = quickCombinationProductMapper.selectListByActivityId(id);

        List<Long> skuIds = new ArrayList<>();
        for(int i = 0; i<products.size(); i++){
            skuIds.add(products.get(i).getSkuId());
        }

        // 拼接返回
        List<ProductSkuDO> skus = productSkuService.getSkuList(skuIds);
        AppProductSpuDetailRespVO detailVO = ProductSpuConvert.INSTANCE.convertForGetSpuDetail(spu, skus);
        // 处理 vip 价格
        MemberLevelRespDTO memberLevel = getMemberLevel();
        detailVO.setVipPrice(calculateVipPrice(detailVO.getPrice(), memberLevel));
        return success(detailVO);
    }

    /**
     * 计算会员 VIP 优惠价格
     *
     * @param price 原价
     * @param memberLevel 会员等级
     * @return 优惠价格
     */
    public Integer calculateVipPrice(Integer price, MemberLevelRespDTO memberLevel) {
        if (memberLevel == null || memberLevel.getDiscountPercent() == null) {
            return 0;
        }
        Integer newPrice = price * memberLevel.getDiscountPercent() / 100;
        return price - newPrice;
    }

    private MemberLevelRespDTO getMemberLevel() {
        Long userId = getLoginUserId();
        if (userId == null) {
            return null;
        }
        MemberUserRespDTO user = memberUserApi.getUser(userId);
        if (user.getLevelId() == null || user.getLevelId() <= 0) {
            return null;
        }
        return memberLevelApi.getMemberLevel(user.getLevelId());
    }


    @GetMapping("/get-detail")
    @Operation(summary = "获得促销活动明细")
    @Parameter(name = "id", description = "活动编号", required = true, example = "1024")
    public CommonResult<QuickCombinationActivityRespVO> getCombinationActivityDetail(@RequestParam("id") Long id) {
        // 1. 获取活动
        QuickCombinationActivityDO activity = quickCombinationActivityService.getQuickCombinationActivity(id);
        if (activity == null
                || ObjectUtil.equal(activity.getStatus(), CommonStatusEnum.DISABLE.getStatus())) {
            return success(null);
        }

        List<QuickCombinationProductDO> products = quickCombinationProductMapper.selectListByActivityId(id);
        List<QuickCombinationProductRespVO> productList = QuickCombinationProductConvert.INSTANCE.convertList(products);
        QuickCombinationActivityRespVO respVO = QuickCombinationActivityConvert.INSTANCE.convert(activity);
        respVO.setProducts(productList);

        return success(respVO);
    }

    @GetMapping("/record-summary")
    @Operation(summary = "获得活动参与列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    public CommonResult<QuickCombinationRecordSummary> getQuickCombinationActivityList(@RequestParam("ids") Collection<Long> ids) {
        QuickCombinationRecordSummary summary = quickCombinationRecordService.getSummary(ids);
        return success(summary);
    }

    @GetMapping("/record")
    @Operation(summary = "获得活动参与列表")
    @Parameter(name = "id", description = "活动编号", required = true, example = "1")
    public CommonResult<List<QuickCombinationRecordRespVO>> getQuickCombinationRecordList(@RequestParam("id") Long id){
        return success(quickCombinationRecordService.getRecorrd(id));
    }
}
